const getSearchInHash = () => {
  const hash = window?.location.hash || '';
  const startPos = hash?.indexOf('?');
  return hash.slice(startPos);
};

/**
 * 兼容url中参数为字符串null，字符串undefined,字符串为0的情况
 */
export const getFormateParam = (value: string | undefined | null) => {
  if (
    typeof value === 'string' &&
    (value === 'null' || value === 'undefined')
  ) {
    return null;
  }
  if (value === 'false') {
    return false;
  }
  if (value === 'true') {
    return true;
  }
  return value;
};

export const getSearchParams = <T extends string>(
  key?: T,
): T extends string ? URLSearchParams : string => {
  const searchText = window?.location?.search || getSearchInHash();
  const search = new URLSearchParams(searchText);
  if (typeof key === 'string') {
    return getFormateParam(search.get(key)) as any;
  } else {
    return search as any;
  }
};

export default getSearchParams;
